<template>
    <div class="details">
        <div class="banner">
            <banner-detail
                    :banner="goodsDetail.diagram"
                    @toShare="toShare"
            />
            <productShare ref="productShare" :product="goodsDetail" type="online"></productShare>
        </div>
        <div class="activity" v-if="goodsDetail.rush">
            <div class="activity-name">{{ goodsDetail.rush.title }}</div>
            <div class="activity-time" v-if="goodsDetail.rush.status">
                距结束
                <span>{{ countDownList.day }}</span>
                天
                <span>{{ countDownList.hour }}</span>
                时
                <span>{{ countDownList.minute }}</span>
                分
                <span>{{ countDownList.second }}</span>
                秒
            </div>
            <div class="activity-time" v-if="!goodsDetail.rush.status">
                开始时间
                <span>{{ getActiveStart }}</span>
            </div>
        </div>
        <div class="info">
            <div class="title" v-text="goodsDetail.name"></div>
            <div class="subtitle" v-text="goodsDetail.dec"></div>
            <div class="current">{{ goodsDetail.price | moneyFmt(2, '￥') }}</div>
            <div class="original">
                <del>原价：{{ goodsDetail.money | moneyFmt(2, '￥') }}</del>
                <span class="stock">库存{{ goodsDetail.stock }}件</span>
                <span class="stock">快递：{{ goodsDetail.postage | moneyFmt(2, '￥') }}</span>
                <span class="volume">月销量{{ goodsDetail.sales }}件</span>
            </div>
        </div>
        <!--<div class="specification" @click="onShowSpec(goodsDetail)">-->
        <div
                class="specification"
                @click="chooseSpec('select', goodsDetail.status)"
                v-if="goodsDetail.sku"
        >
            <span class="spec">规格</span>
            <span class="cho">{{ choice_tip }}</span>
            <span class="icon-right">
                <svg class="icon qb" aria-hidden="true">
                    <use xlink:href="#icon-chevronright"/>
                </svg>
            </span>
        </div>
        <div class="details_img">
            <img :src="item" v-for="(item, index) in goodsDetail.details" :key="index"/>
        </div>
        <div class="group-buy-end" v-if="goodsDetail.status ==3 && goodsDetail.second.status">
            <svg class="icon nz" aria-hidden="true">
                <use xlink:href="#icon-icon--6"/>
            </svg>
            <van-count-down
                    format="HH:mm:ss"
                    @finish="countFinish"
                    :time="Number(goodsDetail.second.time) * 1000"
            />
            后此团购结束
        </div>
        <div v-if="goodsDetail.status != 2">
            <div class="bot-second" v-if="goodsDetail.status == 1 && !goodsDetail.second.status">
                <div class="group-buy-start finish">此商品已下架</div>
            </div>
            <div class="bot" v-else>
                <div class="bot-price">
                    <del>原价：{{ goodsDetail.money | moneyFmt(1, '￥') }}</del>
                    <div class="bot-current">{{ goodsDetail.price | moneyFmt(2, '￥') }}</div>
                </div>
                <div class="bot-cart" @click="toCart">
                    <div class="cart-num" v-if="Number(cartNum) > 0">{{ cartNum }}</div>
                    <svg class="cart" aria-hidden="true">
                        <use xlink:href="#icon-front_car"/>
                    </svg>
                </div>
                <div class="add" @click="chooseSpec('add', goodsDetail.status)">加入购物车</div>
                <div class="buy" @click="chooseSpec('buy', goodsDetail.status)">立即购买</div>
            </div>
        </div>
        <div v-if="goodsDetail.status == 2">
            <div class="bot-presale" v-if="!goodsDetail.second.status">
                <div class="presale-left">
                    <div class="bot-price">
                        <del>原价：{{ goodsDetail.money | moneyFmt(1, '￥') }}</del>
                        <div class="bot-current">{{ goodsDetail.price | moneyFmt(2, '￥') }}</div>
                    </div>
                    <div class="bot-cart" @click="toCart">
                        <div class="cart-num" v-if="Number(cartNum) > 0">{{ cartNum }}</div>
                        <svg class="cart" aria-hidden="true">
                            <use xlink:href="#icon-front_car"/>
                        </svg>
                    </div>
                </div>
                <div class="presale">暂未开售</div>
            </div>
            <div class="bot-second" v-else>
                <div class="group-buy-start">
                    还有
                    <van-count-down
                            @finish="countFinish"
                            format="HH:mm:ss"
                            :time="Number(goodsDetail.second.time) * 1000"
                    />
                    开始
                </div>
            </div>
        </div>
        <product-spec
                :proContent="goodsDetail"
                :operation="operation"
                ref="spec"
                v-if="goodsDetail.name"
                @chooseDone="onChooseDone"
                @showSpecMsg="onSpecMsg"
        />
    </div>
</template>

<script>
    import BannerDetail from '../../components/Online/bannerdetail';
    import productShare from '../../components/Online/product-share';
    import API from '../../request/api';
    import {Toast, CountDown} from 'vant';
    import dayjs from 'dayjs';
    import {commonMixin, wxMixin} from '@/common/mixin';
    import {mapActions} from 'vuex';
    import {protocol} from '@/config';
    import ProductSpec from '../../components/Online/product-spec';
    import {isIOS} from '@/common/utils';

    export default {
        mixins: [commonMixin, wxMixin],
        components: {
            ProductSpec,
            BannerDetail,
            productShare
        },
        name: 'online-detail',
        data() {
            return {
                // isLogin: false, // 是否注册
                // isGuide: false, // 是否显示‘赚’--角色不是普通会员为true
                countDownList: {
                    day: '00',
                    hour: '00',
                    minute: '00',
                    second: '00'
                }, // 活动结束倒计时列表
                goodsDetail: {},
                isShow: false, // 规格弹窗显示
                // isShare: true, // 是否是分享商品
                // specData: {}, // 传进子组件的数据，比goodsDatil多 可选属性列表和长度
                selected: {}, // 已选择的属性
                chooseLists: {},
                choice_tip: '',
                cartNum: 0,
                isLogin: false,
                // systemId: 1,//各系统id
                // sale: this.$route.query.sale,
                gid: this.$route.query.gid,
                operation: '', //弹出商品属性选择框的操作
                share: this.$route.query.share,
                isbuy: false // 是否购买
            };
        },
        computed: {
            systemId() {
                return this.$store.state.login.system;
            },
            getActiveStart() {
                let startTime = Number(this.goodsDetail.rush.starttime) * 1000;
                console.log('startTime', startTime);
                startTime = dayjs(startTime).format('YYYY-MM-DD HH:mm:ss');
                console.log('getActiveStartgetActiveStart', startTime, dayjs());
                return startTime;
            }
        },
        beforeRouteEnter(to, from, next) {
            // 修复iOS版微信h5 History兼容性问题
            if (isIOS() && to.path !== location.pathname) {
                location.assign(to.fullPath); // 此处不可使用location.replace
            } else {
                next();
            }
        },
        async created() {
            // this.showGlobaLoading(); //打开loading
            window.scrollTo(0, 0);
            this.request.get(API.islogin).then(res => {
                if (res.islogin == 1) {
                    // eslint-disable-next-line vue/no-async-in-computed-properties
                    this.request
                        .get(API.getUserInfo)
                        .then(res => {
                            this.$store.commit(
                                'setUserInfo',
                                res
                            );
                            this.isLogin = true;
                        });
                }
            });
            await this.getDetails();
            this.getCartCount();
            if (this.isLogin) {
                this.getIsBuy();
            }
            // 微信分享准备
            this.prepareWxShare(
                `${protocol}://${document.domain}/welcome?referid=${
                    this.userInfo.uid
                    }&page=online-detail&gid=${this.goodsDetail.gid}&sale=${
                    this.goodsDetail.sale
                    }&type=${this.goodsDetail.type}&_from=1024`,
                this.goodsDetail
            );
        },
        methods: {
            ...mapActions(['addToCart']),
            //获取商品详情
            getDetails() {
                // 获取商品详情（全文）
                return this.request
                    .get(API.onlineGetGoodsContent, {
                        gid: this.gid
                    })
                    .then(res => {
                        console.log('onlineGetGoodsContent', res);
                        this.goodsDetail = res;
                        // this.hideGlobaLoading(); //关闭loading
                        this.getGoodsContent();
                        if (res.rush) {
                            if (res.rush.status) {
                                let endTime = Number(res.rush.endtime) * 1000;
                                this.countDown(endTime);
                            }
                            // let endTime = new Date('2019-01-19 18:50:00').getTime()
                        }
                    })
                    .catch(err => {
                        console.error('getDetails', err);
                    });
            },
            getIsBuy() {
                //进这些页面先更新下本地userinfo
                this.request.get(API.getUserInfo).then(res => {
                    this.isbuy = parseInt(res.isbuy) > 0;
                });
            },
            getGoodsContent() {
                let stock = 0;
                let price = Number(this.goodsDetail.sku[0].price);
                let deduction = Number(this.goodsDetail.sku[0].deduction);
                this.goodsDetail.sku.filter(item => {
                    stock = stock + item.stock;
                    // 查找最低价格
                    if (Number(item.price) < price) {
                        price = Number(item.price);
                        deduction = Number(item.deduction);
                    }
                });
                this.goodsDetail.stock = stock;
                this.goodsDetail.price = price;
                this.goodsDetail.deduction = deduction;
            },
            timeFormat(param) {
                return param < 10 ? '0' + param : param;
            },
            //获取活动倒计时列表
            countDown(endTime) {
                let interval = setInterval(() => {
                    // console.log(endTime, 'endTime');
                    // 获取当前时间，同时得到活动结束时间数组
                    let newTime = new Date().getTime();
                    // 对结束时间进行处理渲染到页面
                    let obj = null;
                    // 如果活动未结束，对时间进行处理
                    if (endTime - newTime > 0) {
                        let time = (endTime - newTime) / 1000;
                        // 获取天、时、分、秒
                        let day = parseInt(time / (60 * 60 * 24));
                        let hou = parseInt((time % (60 * 60 * 24)) / 3600);
                        let min = parseInt(((time % (60 * 60 * 24)) % 3600) / 60);
                        let sec = parseInt(((time % (60 * 60 * 24)) % 3600) % 60);
                        obj = {
                            day: this.timeFormat(day),
                            hou: this.timeFormat(hou),
                            min: this.timeFormat(min),
                            sec: this.timeFormat(sec)
                        };
                    } else {
                        // 活动已结束，全部设置为'00'
                        obj = {
                            day: '00',
                            hou: '00',
                            min: '00',
                            sec: '00'
                        };
                        clearInterval(interval);
                    }
                    this.countDownList.day = obj.day;
                    this.countDownList.hour = obj.hou;
                    this.countDownList.minute = obj.min;
                    this.countDownList.second = obj.sec;
                }, 1000);
                // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
                this.$once('hook:beforeDestroy', () => {
                    console.log('beforeDestroy,setTimeout:');
                    clearInterval(interval);
                });
            },
            // 获取购物车数量角标
            getCartCount() {
                if (this.isLogin) {
                    // 获取购物车商品数量
                    this.request
                        .get(API.onlineGetCartCount)
                        .then(result => {
                            this.cartNum = result.count;
                            console.log('onlineGetCartCount', result);
                        })
                        .catch(err => {
                            console.error('onlineGetCartCount-err:', err);
                        });
                } else {
                    console.log(
                        'this.$store.state.online.cart',
                        !!Object.values(this.$store.state.online.cart)[1]
                    );
                    if (Object.values(this.$store.state.online.cart)[1]) {
                        this.cartNum = this.$store.state.online.cart.cartNum[
                            this.systemId
                            ].cartNum;
                    }
                }
            },
            toCart() {
                this.$router.push('cart');
            },
            chooseSpec(opera, status) {
                if (status == 3) {
                    this.operation = opera;
                    // 规格弹窗显示
                    this.$refs.spec.show();
                } else {
                    let tips = '本商品暂无库存'; //0,1-无库存,2-未开售,5-已删除
                    if (status == '2') {
                        tips = '本商品暂未开售';
                    }
                    Toast(tips);
                }
            },
            onSpecMsg(msg) {
                // 规格选择情况
                this.choice_tip = msg;
            },
            //规格选择完毕，加入购物车，需要复制specProduct更改sku属性
            onChooseDone(chooseList, opera) {
                // console.log('onChooseDone--', chooseList, opera);
                if (opera !== 'select') {
                    this.operation = opera;
                }
                this.chooseLists = chooseList;
                // this.chooseLists.num = buyNum;
                this.chooseLists.sale = this.sale;
                this.chooseLists.gid = this.gid;
                this.goodsDetail.price = chooseList.price;
                this.goodsDetail.deduction = chooseList.deduction;
                this.goodsDetail.stock = chooseList.stock;
                if (this.operation === 'buy') {
                    this.buy();
                } else if (this.operation === 'add') {
                    this.add();
                }
            },
            add() {
                // 有没有选择的规格
                if (this.chooseLists.buyid) {
                    if (this.isLogin) {
                        // 购物车添加商品（已注册）
                        this.request
                            .post(API.onlineAddCartGoods, {
                                gid: this.chooseLists.gid,
                                buyid: this.chooseLists.buyid,
                                num: this.chooseLists.count
                            })
                            .then(res => {
                                console.log('onlineAddCartGoods', res);
                                this.getCartCount();
                                Toast('加入购物车成功');
                            })
                            .catch(err => {
                                this.$toast.fail(err);
                            });
                    } else {
                        let sku = this.chooseLists;
                        sku.system = this.$store.state.login.system;
                        this.addToCart(sku);
                        this.getCartCount();
                        Toast('加入购物车成功');
                    }
                } else {
                    // 操作为加入购物车
                    // 规格弹窗显示
                    this.chooseSpec('add');
                }
            },
            buy() {
                // 加是否注册判断
                if (this.isLogin) {
                    if (this.chooseLists.buyid) {
                        let requestArr = [];
                        let requestJson = {};
                        requestJson.buyid = this.chooseLists.buyid;
                        requestJson.gid = this.chooseLists.gid;
                        requestJson.num = this.chooseLists.count;
                        // requestJson.sale = this.chooseLists.sale;
                        requestArr.push(requestJson);
                        let orderData = {
                            data: requestArr,
                            type: this.systemId
                        };

                        console.log('requestJson', requestJson, requestArr);
                        console.log(
                            'this.chooseListsthis.chooseLists',
                            this.chooseLists
                        );
                        this.$store.commit('dataCreateOrder', orderData);
                        this.$router.push({
                            name: 'order-created'
                        });
                    } else {
                        // 操作为加入购物车
                        // 规格弹窗显示
                        this.chooseSpec('buy');
                    }
                } else {
                    this.$router.push({
                        name: 'login',
                        query: {
                            direct: 'order-created'
                        }
                    });
                    // this.$store.commit('loginShow', true);
                }
            },
            toShare() {
                this.$refs.productShare.show();
            },
            countFinish() {
                location.reload();
            }
        },
        beforeRouteLeave(to, from, next) {
            // 商品详情页back时：如果是分享进入，back to front页面
            if (this.share && to.name == 'welcome') {
                this.$router.push({
                    name: 'front'
                });
            } else {
                next();
            }
        }
    };
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
    @import '~@/assets/main.styl';

    .details {
        margin-left: 0;
        margin-bottom: vw(50);
        overflow-x: hidden;
    }

    .activity {
        width: 100%;
        height: vw(50);
        background: url(backImg) 100% 100% no-repeat;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: grayF;

        .activity-name {
            padding-left: cellPadding;
            font-size: word14;
            line-height: vw(19);
        }

        .activity-time {
            padding-right: cellPadding;
            font-size: word12;
            line-height: vw(16);

            span {
                width: vw(10);
                color: #FAD11B;
                /* border 1px blue solid */
            }
        }
    }

    .info {
        margin-top: smallMargin;
        padding-left: smallMargin;
        padding-top: smallMargin;
        width: 100%;
        height: vw(115);
        background-color: grayF;

        .title {
            word-vw(word14, gray3);
            height: vw(16);
            line-height: vw(16);
        }

        .subtitle {
            word-vw(word12, gray9);
            margin-top: titleMargin;
            height: vw(16);
            line-height: vw(16);
            ellipsis();
        }

        .original {
            word-vw(word12, gray9);
            margin-top: smallMargin;
            height: vw(16);
            line-height: vw(16);
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            width: 100%;

            .volume {
                position: relative;
                margin-right: middleMargin;
            }
        }

        .current {
            word-vw(word16, main-color);
            margin-top: smallMargin;
            height: vw(21);
            line-height: vw(21);
        }
    }

    .specification {
        margin-top: smallMargin;
        height: vw(40);
        width: 100%;
        background-color: grayF;
        padding-left: smallMargin;
        display: flex;
        align-items: center;

        .icon-right {
            position: absolute;
            right: smallMargin;

            .qb {
                width: vw(8);
                height: vw(13);
                overflow: hidden;
                fill: gray9;
            }
        }

        .spec {
            word-vw(word16, gray3);
        }

        .cho {
            word-vw(word16, gray9);
            margin-left: middleMargin;
            ellipsis();
            width: 80%;
        }
    }

    .details_img {
        margin-top: smallMargin;

        img {
            width: 100%;
            display: flex;
            float: top;
        }
    }

    .group-buy-end {
        width: vw(211);
        height: vw(25);
        background: grayF;
        border-radius: all-radius;
        position: fixed;
        bottom: vw(65);
        left: 25%;
        flex-x(center);
        word-vw(word12, main-color);
        line-height: vw(16);

        .van-count-down {
            word-vw(word12, main-color);
            line-height: vw(16);
        }

        .icon {
            width: vw(15);
            height: vw(15);
            fill: main-color;
            margin-right: vw(5);
        }
    }

    .bot {
        position: fixed;
        background-color: grayF;
        width: 100%;
        height: vw(50);
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 smallMargin;
        box-sizing: border-box;
        font-size: word16;
        bottom: 0;

        .bot-price {
            del {
                word-vw(word12, gray9);
                line-height: vw(16);
            }

            .bot-current {
                word-vw(word14, gray3);
                line-height: vw(19);
            }
        }

        .bot-cart {
            .cart {
                width: vw(26);
                height: vw(24);
            }

            .cart-num {
                word-vw(word12, grayF);
                display: flex;
                text-align: center;
                justify-content: center;
                align-items: center;
                background-color: main-color;
                border-radius: all-radius;
                width: vw(18);
                height: vw(18);
                position: fixed;
                z-index: 100;
                margin-left: vw(12);
                margin-top: vw(-5);
            }
        }

        .buy {
            secondary-solid();
            display: inline-flex;
            justify-content: center;
            align-items: center;
        }

        .add {
            // secondary-hollow()
            display: inline-flex;
            justify-content: center;
            align-items: center;
        }

        .no {
            color: gray9;
            border-color: gray9;
        }
    }

    .bot-presale {
        position: fixed;
        background-color: grayF;
        width: 100%;
        height: vw(50);
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 smallMargin;
        box-sizing: border-box;
        font-size: word16;
        bottom: 0;

        .presale-left {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            width: 35%;

            .bot-price {
                del {
                    word-vw(word12, gray9);
                    line-height: vw(16);
                }

                .bot-current {
                    word-vw(word14, gray3);
                    line-height: vw(19);
                }
            }

            .bot-cart {
                .cart {
                    width: vw(26);
                    height: vw(24);
                }

                .cart-num {
                    word-vw(word12, grayF);
                    display: flex;
                    text-align: center;
                    justify-content: center;
                    align-items: center;
                    background-color: main-color;
                    border-radius: all-radius;
                    width: vw(18);
                    height: vw(18);
                    position: fixed;
                    z-index: 100;
                    margin-left: vw(12);
                    margin-top: vw(-5);
                }
            }
        }

        .presale {
            secondary-solid();
        }
    }

    .bot-second {
        width: 100%;
        height: vw(55);
        background: grayF;
        position: fixed;
        bottom: 0;
        left: 0;
        flex-x(center);

        .group-buy-start {
            flex-x(center);
            width: vw(200);
            height: vw(35);
            background: #F3F3F3;
            border-radius: all-radius;
            flex-x(center);
            word-vw(word14, main-color);
            line-height: vw(19);

            .van-count-down {
                word-vw(word14, main-color);
                line-height: vw(19);
            }

            &.finish {
                color: gray6;
            }
        }
    }
</style>
